﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SetupHandler.cs" company="Anton Frattaroli">
//   Copyright (c) Anton Frattaroli. All rights reserved.
// </copyright>
// <summary>
//   Defines the SetupHandler IHttpHanlder implementation class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Lidocaine.Service
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Web;
    using System.Xml;
    using Lidocaine.BusinessLogic;
    using Lidocaine.BusinessObjects;
    
    /// <summary>
    /// Defines the SetupHandler class.
    /// </summary>
    public class SetupHandler : IHttpHandler
    {
        /// <summary>Gets a value indicating whether this implementation of IHttpHandler is reusable.</summary>
        public bool IsReusable
        {
            get { return false; }
        }
        
        /// <summary>
        /// This implementation of IHttpHandler handles one of two asynchronous calls the Lidocaine installation webpage makes.
        /// </summary>
        /// <param name="context">The HttpContext object of the current HTTP request.</param>
        public void ProcessRequest(HttpContext context)
        {
            if (BusinessLogic.Environment.AllowSetup)
            {
                try
                {
                    UserProfile profile = InstallerManager.Setup(context.Request["siteDomain"]);
                    UserProfileManager.LogOn(profile, true);

                    DeveloperControl developerControl = new DeveloperControl();
                    developerControl.Description = "The Lidocaine error handler.";
                    developerControl.Name = "Error";
                    developerControl.Path = "Error.ascx";
                    developerControl = DeveloperControlManager.SaveAs(developerControl);

                    PageLayout page = PageLayoutManager.New();
                    page.Path = "Error.aspx";
                    page.Title = "An Error Occurred.";
                    page = PageLayoutManager.SaveAs(page);

                    string pageHtml = "<h3>Oops... an error occurred.<h3><div class=\"developerControlPlaceholder " + developerControl.Id + "\" style=\"float:none;\">&nbsp;</div>";
                    PageLayoutManager.SaveAndPublishContent(page, pageHtml, profile);

                    developerControl = new DeveloperControl();
                    developerControl.Description = "The Lidocaine logon handler.";
                    developerControl.Name = "LogOn";
                    developerControl.Path = "LogOn.ascx";
                    developerControl = DeveloperControlManager.SaveAs(developerControl);

                    page = PageLayoutManager.New();
                    page.Path = "LogOn.aspx";
                    page.Title = "Log On";
                    page = PageLayoutManager.SaveAs(page);

                    pageHtml = "<h3>Log On<h3><div class=\"developerControlPlaceholder " + developerControl.Id + "\" style=\"float:none;\">&nbsp;</div>";
                    PageLayoutManager.SaveAndPublishContent(page, pageHtml, profile);

                    XmlDocument existingConfig = new XmlDocument();
                    using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath("~/") + "web.config"))
                    {
                        existingConfig.Load(sr);
                    }

                    // Lidocaine appConfig
                    XmlNode appConfig = existingConfig.SelectSingleNode("/configuration/lidocaine/appConfig");
                    appConfig.Attributes["allowSetup"].Value = "false";
                    appConfig.ParentNode.ReplaceChild(appConfig, existingConfig.SelectSingleNode("/configuration/lidocaine/appConfig"));
                    using (StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath("~/") + "web.config"))
                    {
                        existingConfig.Save(sw);
                    }
                }
                catch (Exception ex)
                {
                    context.Response.StatusCode = 500;
                    context.Response.Write("Failed to set up application: " + ex.Message + "<br />" + ex.InnerException);
                }
            }
        }
    }
}